#include "genericservice.h"

GenericService::GenericService(QString url, QObject *parent)
    : QObject(parent)
{
    this->mUrl = url;
}

void GenericService::setUrl(QString url)
{
    this->mUrl = url;
}

void GenericService::get(Service *service, QString args)
{
    QObject::disconnect(service,SIGNAL(responseReceived(const QByteArray&)),0,0);
    QObject::disconnect(service,SIGNAL(networkError(QNetworkReply::NetworkError)),0,0);

    QObject::connect(service ,SIGNAL(responseReceived(const QByteArray&)),
                     this,SLOT(serviceResponseReceived(const QByteArray &)));

    QObject::connect(service ,SIGNAL(networkError(QNetworkReply::NetworkError)),
                     this,SLOT(serviceNetworkError(QNetworkReply::NetworkError)));

    QString url(this->mUrl);

    if(!args.isEmpty()) {
        url.append(args);
    }

    service->callServiceGET(url);
}

void GenericService::post(Service *service, QString data)
{
    QObject::disconnect(service,SIGNAL(responseReceived(const QByteArray&)),0,0);
    QObject::disconnect(service,SIGNAL(networkError(QNetworkReply::NetworkError)),0,0);

    QObject::connect(service ,SIGNAL(responseReceived(const QByteArray&)),
                     this,SLOT(serviceResponseReceived(const QByteArray &)));

    QObject::connect(service ,SIGNAL(networkError(QNetworkReply::NetworkError)),
                     this,SLOT(serviceNetworkError(QNetworkReply::NetworkError)));

    service->callServicePOST(this->mUrl,data);
}

void GenericService::serviceResponseReceived(const QByteArray &data) {
    emit responseReceived(data);
}

void GenericService::serviceNetworkError(QNetworkReply::NetworkError err) {
    emit networkError(err);
}
